function loores = ecogSpiderNfoldCV( N,TRAIN, OBJECTIVE, C)
% loores = leaveOneOut( TRAIN, OBJECTIVE, C)
% TRAIN - the train data; format: TRAIN(trial,featureNumber)
% OBJECTIVE - the corresponding class labels -1 and 1. zeros labeled data 
% will be deleted
% C - penalty parameter (optional) default: see Joachims

if exist('svm','file')~=2,
    addpath /octo1/reichert/mr_scripts/spider/
    use_spider;
end

d_idx = find(OBJECTIVE ==0);
if ~isempty(d_idx),
    OBJECTIVE(d_idx)=[];
    TRAIN(d_idx,:)=[];
    fprintf('%i datapoints discarded from trainset.\n',length(d_idx));
end

numberNeg = sum(OBJECTIVE<0);
numberPos = sum(OBJECTIVE>0);

if nargin == 3,
    C=[];
end

predictions=zeros(size(OBJECTIVE));
loores.losses=zeros(1,N);
SVs=zeros(1,N);
    
% set classification algorithm
alg = svm;
alg.optimizer='libsvm';
% --------------------------------------
% create subsets
r_idx = randperm(length(OBJECTIVE));
Nn = floor(length(r_idx)/N);
Nr = mod(length(r_idx),N);
%  N fold CV loop
    for k=1:N,
        fprintf('Fold %i\n',k);
        left_idx = r_idx((k-1)*Nn+1:k*Nn);
        if k==N && Nr>0,
            left_idx = [left_idx, r_idx(k*Nn+1:k*Nn+Nr)];
        end
        used_idx = setdiff(1:length(r_idx),left_idx);
        if isempty(C),
            % determine default C according to Joachims
            scalar_prod=zeros(1,length(used_idx));
            for kk=1:length(used_idx), 
                scalar_prod(kk)=TRAIN(used_idx(kk),:)*TRAIN(used_idx(kk),:)';
            end
            alg.C=1/mean(scalar_prod);
        else 
            alg.C=C;
        end
        curTRAIN=TRAIN(used_idx,:);
        curOBJECTIVE=OBJECTIVE(used_idx);
        d = data(curTRAIN,curOBJECTIVE);
        % suppress output
        evalc('[tr res_alg] = train(alg,d)');
        loores.losses(k) = sum(tr.X~=tr.Y)/length(tr.X);
        SVs(k)=sum(abs(res_alg.alpha)>0)/length(tr.X);
        tst_d=data(TRAIN(k,:),OBJECTIVE(k));
        tst=test(res_alg, tst_d);
        predictions(left_idx)=tst.X;
    end
    loores.prediction = predictions;
    loores.pred_acc = mean(predictions==OBJECTIVE);
    loores.rec1 = sum(predictions==OBJECTIVE&OBJECTIVE>0)/sum(OBJECTIVE>0);
    loores.rec2 = sum(predictions==OBJECTIVE&OBJECTIVE<0)/sum(OBJECTIVE<0);
    loores.prec1 = sum(predictions>0&OBJECTIVE>0)/...
                (sum(predictions>0&OBJECTIVE>0)+sum(predictions>0&OBJECTIVE<0));
    loores.prec2 = sum(predictions<0&OBJECTIVE<0)/...
                (sum(predictions<0&OBJECTIVE<0)+sum(predictions<0&OBJECTIVE>0));
    loores.err_on_trainset = mean(loores.losses);
    loores.SV=mean(SVs);
    loores.N1 = numberNeg;
    loores.N2 = numberPos;